-- tests scene
local layer = nil
local scene = nil

local Btn_Tips  = 0x01
local Btn_Item1 = 0x02
local Btn_Item2 = 0x03
local Btn_Item3 = 0x04

--新砖块初始创建时间
local BizzNewLineTimeBase = 5
-- 每金币的等级
local BizzCrystalLevel = 5
-- 速度提升率
local BizzNewLineLvS = 0.02
--水晶模式积分水晶币
local GCrystalToScore = 5000


local function initWithLayer()
    -- 暴走模式开启时机
    local _baozoutime = 0
    local _onbaozou = false
    local _func_onShowResult = nil
    local _on_result = false
    
    local _lastCombo = 0
    local _iCombo = 1
    
    local _btnItem_Baozou = nil
    local _btnItem_AutoSl= nil
    
    
    -- 新宝石生成时间(初始5秒
    _GameMode_Bizz_NewLine = BizzNewLineTimeBase
    -- 本局总时间
    local _PlayGameTime = GPlayGameTime
    -- 停止掉的时间(时间停止道具
    local _PlayGameStopTime = 0
    -- 剩余需要停止的时间
    local _PlayGameStopLastTime = 0
    -- 无限暴走
    local _OnBaoForever = false
    -- 游戏时间
    local _gameRunTime = 0
    
    
    -- 按钮回调函数
    local function menuCallback(tag)
        if tag == Btn_Tips then
            for r=0,Gems_Rows-1 do
                for c=0,Gems_Cols-1 do
                    local cgem = _GGemTable[getIndex(r,c)]
                    if cgem then
                        print(r,c,cgem.row, cgem.col)
                    else
                        print(r,c,cgem)
                    end
                end
            end
        elseif tag == Btn_Item1 then
            --_func_onShowResult()
        elseif tag == Btn_Item2 then
        elseif tag == Btn_Item3 then
        end
        
        Play_Effect(sme_Click)
    end
    -------- ui
    
    --- 进度条
    --- 背景
    _bgpx = 38
    _bgpy = DWinSizeHeight - 150
    local _GameProgressBG = CCSprite:createWithSpriteFrameName("HLWS_T0.png")
    _GameProgressBG:setAnchorPoint(ccp(0, 0.5))
    _GameProgressBG:setPosition(gdccp(_bgpx, _bgpy))
    layer:addChild(_GameProgressBG, 2)
    
    local _GameProgress = CCProgressTimer:create(CCSprite:createWithSpriteFrameName("HLWS_T1.png"))
    _GameProgress:setType(kCCProgressTimerTypeBar)
    _GameProgress:setAnchorPoint(ccp(0, 0.5))
    _GameProgress:setMidpoint(CCPointMake(0, 0))
    _GameProgress:setBarChangeRate(CCPointMake(1, 0))
    _GameProgress:setPosition(gdccp(_bgpx, _bgpy))
	layer:addChild(_GameProgress,2)
    
    -- 游戏等级
    local _spbg = CCSprite:createWithSpriteFrameName("LvIcon.png")
    _spbg:setAnchorPoint(ccp(1, 0.5))
    _spbg:setPosition(gdccp(180, DWinSizeHeight-25))
    layer:addChild(_spbg, 2)
    
    local _gui_level = GameNumbers:new(vNumberScore, NumberAlginment_Left)
    _gui_level:addLayer(layer, LayerIdx_Gui)
    _gui_level:setNumber(1)
    _gui_level:setPosition(gdccp(190, DWinSizeHeight-25))
    
    -- 分数
    local _gui_hl = CCSprite:createWithSpriteFrameName("GUI_SC.png")
    _gui_hl:setPosition(gdccp(120, DWinSizeHeight-40))
    layer:addChild(_gui_hl, LayerIdx_Gui)
    
    local _lblScore = GameNumbers:new(vNumberScore, NumberAlginment_Left, nil, 7, true)
    _lblScore:addLayer(layer, LayerIdx_Gui)
    _lblScore:setNumber(0)
    _lblScore:setPosition(gdccp(150, DWinSizeHeight-66))
    
    -- 水晶
    local _gui_hl = CCSprite:createWithSpriteFrameName("GUI_SJ.png")
    _gui_hl:setPosition(gdccp(400, DWinSizeHeight-40))
    layer:addChild(_gui_hl, LayerIdx_Gui)
    
    local _lblCrystal = GameNumbers:new(vNumberCrytal)
    _lblCrystal:addLayer(layer, LayerIdx_Gui)
    _lblCrystal:setNumber(0)
    _lblCrystal:setPosition(gdccp(450, DWinSizeHeight-42))
    
    local function updateItemsCount()
        _btnItem_Baozou:updateCut(GetItems(Item_Baozou))
        _btnItem_AutoSl:updateCut(GetItems(Item_AutoSl))
    end
    
    -- 创建一个主菜单
    local _Menu = CCMenu:create()
    
    
    local function menuCallbackItem(tag)
        --_func_onShowResult(true)
        if tag == Item_Baozou then
            if not _OnBaoForever then
                if UseItems(Item_Baozou) then
                    _OnBaoForever = true
                    GFunc_ShowBaozouEffs()
                end
            else
                Play_Effect(sme_ClickError)
            end
        elseif tag == Item_AutoSl then
            local cgemss = nil
            local idx = 0
            while true do
                local irow = Gems_Rows-1
                local icol = idx
                idx = idx + 1
                cgemss = _GGemTable[getIndex(irow,icol)]
                if cgemss or idx > Gems_Cols then
                    break
                end
            end
            if cgemss and UseItems(Item_AutoSl) then
                _func_UseToBom(cgemss, Item_Bom)
            end
        end
        
        --Play_Effect(sme_Click)
        updateItemsCount()
    end
    
    
    local invW = 200
    local invSums = 2
    local bpx = DWinSizeWidth/2 + (1-invSums)*invW/2
    local bpy = 60
    local index = 0
    
    local layerItems = CCLayer:create()
    layer:addChild(layerItems, LayerIdx_Gui)
    
    
    _btnItem_AutoSl = GameItems:new(Item_AutoSl, menuCallbackItem)
    _btnItem_AutoSl:setPosition(bpx + invW * index, bpy)
    _btnItem_AutoSl:addToChild(layerItems)
    index = index + 1
    
    _btnItem_Baozou = GameItems:new(Item_Baozou, menuCallbackItem)
    _btnItem_Baozou:setPosition(bpx + invW * index, bpy)
    _btnItem_Baozou:addToChild(layerItems)
    
    updateItemsCount()
    
    ---- 主菜单大小
    _Menu:setContentSize(CCSizeMake(DWinSizeWidth,  DWinSizeHeight))
    ---- 设置坐标
    _Menu:setPosition(0, 0)
    ---- 添加至主菜单层
    layer:addChild(_Menu, LayerIdx_Gui)
    
    
    -------------------------
    -- 初始宝石
    local gemType = {Gem_Blue, Gem_Cyan, Gem_Purple, Gem_Green}
    -- 总分数
    local _gameScore = 0
    local _gameSoulPer = 0
    local _gameCrystal = 0 -- 当前水晶币
    local _comboSums = 0-- 累加消除数
    local _Level = 1
    
    local userdefalut = CCUserDefault:sharedUserDefault()
    --print("___stageData___",GetSJSKDatas())
    
    --获取关卡相关信息,传递到消除游戏逻辑类初始化中
    
    
    
    ---- 显示游戏结果
    _func_onShowResult = function ()
        if _on_result then
            return
        end
        _on_result = true
        
        --GamePasueHelper()
        _GameEndRun = true
        
        -- 重新开始
        local function onRestStage()
            Create_SJSK_SceneRun()
            
            Play_Effect(sme_Click)
        end
    
        ------- 显示结果
        local layerRestul = CCLayerColor:create(ccc4(0,0,0,80))
        local ResultMainMenu = CCMenu:create()
        -- 主菜单大小
        ResultMainMenu:setContentSize(CCSizeMake(DWinSizeWidth,  DWinSizeHeight))
        -- 设置坐标
        ResultMainMenu:setPosition(0, 0)
        -- 添加至主菜单层
        layerRestul:addChild(ResultMainMenu, 5)
        scene:addChild(layerRestul, 5)
        
        --- 遮罩
        local btnItem = nil
        btnItem = CCMenuItemLabel:create(CCLabelTTF:create("", "Arial", FontSize))
        btnItem:setPosition(gdccp(DWinSizeWidth/2, DWinSizeHeight/2))
        btnItem:setContentSize(CCSizeMake(DWinSizeWidth,  DWinSizeHeight))
        ResultMainMenu:addChild(btnItem,100)
            
        _bgSpr = CCSprite:createWithSpriteFrameName(s_Game_LostImgBG)
        _bgSpr:setPosition(gdccp(DWinSizeWidth/2, DWinSizeHeight/2))
        layerRestul:addChild(_bgSpr)
        _bgSpr = CCSprite:createWithSpriteFrameName(s_Game_LostImg)
        _bgSpr:setPosition(gdccp(DWinSizeWidth/2, DWinSizeHeight/2+150))
        layerRestul:addChild(_bgSpr)
        
        -- 最后一关之前
        local invW = 200
        local invSums = 2
        local bpx = DWinSizeWidth/2 + (1-invSums)*invW/2
        local bpy = DWinSizeHeight/2 - 80
        local index = 0
        
        local btnItem = GFunc_CreateButtonP("rst_rest.png", onRestStage)
        btnItem:setPosition(gdccp(bpx + invW * index, bpy))
        ResultMainMenu:addChild(btnItem)
        index = index + 1
        
        local btnItem = GFunc_CreateButtonP("fh_return.png", MainMenuCallback)
        btnItem:setPosition(gdccp(bpx + invW * index, bpy))
        ResultMainMenu:addChild(btnItem)
        
        
        --显示魂力值与分数
        local spriteHL = CCSprite:createWithSpriteFrameName("rst_score.png")
        spriteHL:setPosition(gdccp(DWinSizeWidth/2 - 150, DWinSizeHeight/2+60))
        layerRestul:addChild(spriteHL)
        spriteHL = CCSprite:createWithSpriteFrameName("rst_crytal.png")
        spriteHL:setPosition(gdccp(DWinSizeWidth/2 - 150, DWinSizeHeight/2))
        layerRestul:addChild(spriteHL)
        
        local txthl = CCLabelTTF:create(_gameScore, "Arial", FontSize4)
        txthl:setPosition(gdccp(DWinSizeWidth/2 + 50, DWinSizeHeight/2+60))
        layerRestul:addChild(txthl)
        
        txthl = CCLabelTTF:create(_gameCrystal, "Arial", FontSize4)
        txthl:setPosition(gdccp(DWinSizeWidth/2 + 50, DWinSizeHeight/2))
        layerRestul:addChild(txthl)
        
        Play_BackgroundMusic(sm_Lost)
        Func_DataStatis(DS_Score, _gameScore)
    end
    
    --------------------- 游戏事件回调
    local function gameComplete()
        --判断是否已经被填充满了,满了则结束游戏
        local isnull = false
        local creRows = Gems_Rows-1
        local creCols = Gems_Cols-1
        for r = 0, creRows do
            for c = 0, creCols do
                if _GGemTable[getIndex(r,c)] == nil then
                    --print(r,c)
                    isnull = true
                    break
                end
            end
            if isnull then
                break
            end
        end
        --print("_isnull",isnull)
        if not isnull then
            -- 游戏结束
            -- 增加水晶币
            --local adcry = _gameCrystal
            --AddCrystal(adcry)
            
            -- 计算判定是否过关
            local ld_score = GetSJSKDatas()
            -- 分数更新当前关卡
            if _gameScore > ld_score then
                UpdateSJSKDatas(_gameScore)
            end
            _func_onShowResult()
        end
    end
    local function gameAddScene(v)
        print("gameAddScene",v)
    end
    local function gameCombo(icombo, gemsums, bomgem)
        if _lastCombo < 2.0 then
            _iCombo = _iCombo + 1
            Func_DataStatis(DS_Combo, _iCombo)
        else
            _iCombo = 1
        end
        _lastCombo = 0
        
        
        --显示连击数
        if bomgem~=nil then
            GFunc_ComboEffs(_iCombo, ccp(bomgem:GetPosition()))
        end
        
        -- 计算分数
        -- 分数=(消除个数+2) * 10
        -- 魂力值=消除个数+2
        -- 得分=分数*连击数
        local score = (gemsums + 2) * 10
        local soulper = (gemsums + 2)
        Func_DataStatis(DS_HunJing, gemsums)
        
        -- 如果连击数大于8,则分数倍数=16
        local scoreCombo = _iCombo
        -- 如果连击数大于8,则魂力值倍数=12
        local soulperCombo = _iCombo
        if _iCombo >= 8 and _onbaozou == false then
            _baozoutime = 0
            _onbaozou = true
            -- 暴走模式已经开启
            Func_DataStatis(DS_Baozou)
            
            
            GFunc_ShowBaozouEffs()
        end
        if _onbaozou or _OnBaoForever then
            scoreCombo = 16
            soulperCombo = 12
        end
        
        local addScore = score * scoreCombo
        local addSoulper = soulper * soulperCombo
        
        
        -- 计分
        _gameScore = _gameScore + addScore
        _gameSoulPer= _gameSoulPer + addSoulper
        
        _lblScore:setNumber(_gameScore)
        -- 水晶币
        local lcrystal = _gameCrystal
        _gameCrystal = math.floor(_gameScore/GCrystalToScore)
        _lblCrystal:setNumber(_gameCrystal)
        
        --水晶币进度条
        _GameProgress:setPercentage(_gameScore%GCrystalToScore/GCrystalToScore * 100)
        -- 根据水晶币的数量,提升砖块下落速度
        if lcrystal ~= _gameCrystal then
            -- 等级为金币数量/5 + 1
            local lv = math.floor(_gameCrystal/BizzCrystalLevel) + 1
            if _Level ~= lv then
                _gui_level:setString(string.format("Lv:%d",lv))
                -- 速度公式 1+1*20%*7*20%=1.28
                local newsp = BizzNewLineTimeBase / math.pow((1+BizzNewLineLvS), lv-1)
                _GameMode_Bizz_NewLine = newsp
            end
            
            --即时增加水晶
            AddCrystal(1)
        end
        
        
        --- 根据连击数增加关卡难度
        _comboSums = _comboSums + 1
        local UgemTypes = gemType
        local fillType = FillType_Down
        if _comboSums > 40 then
            UgemTypes = {Gem_Red, Gem_White, Gem_Blue, Gem_Cyan, Gem_Purple, Gem_Green}
            fillType = FillType_Up
        elseif _comboSums > 30 then
            fillType = FillType_Up
            UgemTypes = {Gem_White, Gem_Blue, Gem_Cyan, Gem_Purple, Gem_Green}
        elseif _comboSums > 20 then
            UgemTypes = {Gem_Blue, Gem_Cyan, Gem_Purple, Gem_Green}
            fillType = FillType_Up
        end
        G_PuzGemsList = UgemTypes
        G_FillTypeBizz = fillType
    end
    local function gameKills(v)
    end
    local function onHurt(v)
    end
    local function onTimer(frame, dt)
        if _onbaozou then
            _baozoutime = _baozoutime + dt
            --- 暴走计时
            if _baozoutime > GBaoZouTimer then
                _onbaozou = false
                if not _OnBaoForever then
                    Gfunc_DelBazouEffs()
                end
            end
        end
        
        _lastCombo = _lastCombo + dt
        
    end
    
    local gamefunc = {
        [PFunc_Complete] = gameComplete,
        [PFunc_AddScore] = gameAddScene,
        [PFunc_Combo] = gameCombo,
        [PFunc_Kills] = gameKills,
        [PFunc_Hurts] = onHurt,
        [PFunc_Timer] = onTimer,
    }
    
    
    local function onTouchEnded(x, y)
    end

    local function onTouch(eventType, x, y)
    end
    
    layer:setTouchEnabled(true)
    layer:registerScriptTouchHandler(onTouch)
    
    -- 三消游戏UI
    
    -- 宝石填充模式
    G_FillTypeBizz = FillType_Down
    layer:addChild(Create_Game_Scene(GameMode_Bizz, gemType, PlayMode_ShouJi, gamefunc),3)
    
    -- 背景
    --背景循环
    local _bglist = {"FB_py.png", "FB_ss.png", "FB_hb.png", "FB_cb.png"}
    local sbgfile = _bglist[math.random(1, #_bglist)]
        
        
        
    local _bgSprite = CCSprite:createWithSpriteFrameName(sbgfile)
    _bgSprite:setAnchorPoint(ccp(0, 0))
    layer:addChild(_bgSprite, 0)
    
    local _bgpx = 0
    local _bgpy = 133
    local _bg2px = 0
    local _bg2py = 0
    
    local _bgBrick = CCSprite:createWithSpriteFrameName(s_ShoujiBg)
    _bgBrick:setAnchorPoint(ccp(0, 0))
    _bgBrick:setPosition(gdccp(_bgpx, _bgpy))
    layer:addChild(_bgBrick, 1)
    -- 背景2
    local _bgBrick2 = CCSprite:createWithSpriteFrameName(s_ShoujiBg2)
    _bgBrick2:setAnchorPoint(ccp(0, 0))
    _bgBrick2:setPosition(gdccp(_bg2px, _bg2py))
    layer:addChild(_bgBrick2, 2)
    
    Func_ShowGameTutorial(UI_SJSK_Game, function()
        Func_BeginResFills()
    end, scene)

    return layer
end

--------------------------------
-- Click And Move Test
--------------------------------
function Create_SJSK_SceneRun()
    scene = CCScene:create()
    layer = CCLayer:create()
    scene:addChild(layer)

    initWithLayer()

    scene:addChild(CreateGameStopLayer(ccp(50, DWinSizeHeight-50)))
    
    -- 收集模式减少体力
    RedTili()

    GameSetScne(scene, UI_SJSK_Game)
end

function Create_SJSK_Scene()
    LoadingTutorial(UI_SJSK_Game, Create_SJSK_SceneRun)
end
